﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAKEJI.Abp.ChineseChar;
using YAKEJI.Xaf.DataDictionaries;
using YAPACS.BusinessObjects.Exams;
using YAPACS.RisServer.Interface.Imitate.ExamDetail;
using YAPACS.RisServer.Services.Dtos;

namespace YAPACS.RisServer.Controllers;

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class PatientController : AbpControllerBase
{
    private readonly IMapper _mapper;
    private readonly IPatinetFilter _patinetFilter;
    private readonly IRepository<DataDictItem, Guid> _dataDictItemRepository;
    private readonly IRepository<Patient, Guid> _pateintRepository;
    private readonly IChineseCharProvider _chineseCharProvider;

    public PatientController(IRepository<DataDictItem, Guid> dataDictItemRepository,
        IPatinetFilter patinetFilter,
        IRepository<Patient, Guid> pateintRepository,
        IMapper mapper,
        IChineseCharProvider chineseCharProvider)
    {
        _dataDictItemRepository = dataDictItemRepository;
        _patinetFilter = patinetFilter;
        _pateintRepository = pateintRepository;
        _mapper = mapper;
        _chineseCharProvider = chineseCharProvider;
    }

    [HttpGet("get-patient-list")]
    public async Task<IActionResult> GetPatientList(string Name, string OldName, string ParentName, string IdCardTypeID, string IdCardNumber, string MedicalInsuranceType, string MedicalInsuranceNumber,string PhoneNumber,string PhoneNumber2,int page,int perPage)
    {
        //获取证件类型对象
        DataDictItem idCardType = null;
        if (!string.IsNullOrEmpty(IdCardTypeID))
        {
            idCardType = await _dataDictItemRepository.GetAsync(Guid.Parse(IdCardTypeID));
        }

        DataDictItem medicalInsuranceType = null;
        if (!string.IsNullOrEmpty(MedicalInsuranceType))
        {
            medicalInsuranceType = await _dataDictItemRepository.GetAsync(Guid.Parse(MedicalInsuranceType));
        }

        _patinetFilter.SetProperties(Name, OldName, ParentName, idCardType, IdCardNumber, medicalInsuranceType, MedicalInsuranceNumber, PhoneNumber,PhoneNumber2);
        Expression<Func<Patient, bool>> expr = _patinetFilter.ToExpression(); //  生成过滤表达式
        var list = await _pateintRepository.GetListAsync(expr);
        List<PatientDto> result = _mapper.Map<List<Patient>, List<PatientDto>>(list);//.Skip((page--)*perPage).Take(perPage).ToList()
        return Ok(new { rows = result , count=list.Count});
    }

    [HttpGet]
    [Route("convert-to-pinyin")]
    public async Task<IActionResult> ConvertToPinYin(string name)
    {
        var result = await _chineseCharProvider.GetPinYinAsync(name);
        var namePinYin= string.Join("", result);
        return Ok(new { namePinYin });
    }
}
